import 'package:bloc/bloc.dart';

/// 定义事件
enum CounterEvent { increment, decrement }

/// 定义Bloc, 必须继承Bloc
class CounterBloc extends Bloc<CounterEvent, int> {
  // 必须实现初始化状态
  @override
  int get initialState => 0;

  // 必须实现mapEventToState方法
  @override
  Stream<int> mapEventToState(CounterEvent event) async* {
    // 根据不同的事件做处理
    switch (event) {
      case CounterEvent.increment: // 添加事件
        yield state + 1;
        break;
      case CounterEvent.decrement: // 减少事件
        yield state - 1;
        break;
      default:
        throw Exception('unhandled event: $event');
    }
  }

  // 记录转换过程
  @override
  void onTransition(Transition<CounterEvent, int> transition) {
    print(transition);
  }

  // 异常
  @override
  void onError(Object error, StackTrace stacktrace) {
    print('$error');
  }
}

/// Bloc 代理
class SimpleBlocDelegate extends BlocDelegate {
  @override
  void onEvent(Bloc bloc, Object event) {
    super.onEvent(bloc, event);
    print('SimpleBlocDelegate: onEvent');
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    print('SimpleBlocDelegate: onTransition');
  }

  @override
  void onError(Bloc bloc, Object error, StackTrace stacktrace) {
    super.onError(bloc, error, stacktrace);
    print('SimpleBlocDelegate: onError');
  }
}

void main(List<String> args) {
  // 单例对象
  BlocSupervisor.delegate = SimpleBlocDelegate();
  // 创建Bloc
  var bloc = CounterBloc();

  // 添加事件
  for (var i = 0; i < 3; i++) {
    bloc.add(CounterEvent.increment);
  }

  // 添加null
  bloc.add(null);

  // 添加事件
  for (var i = 0; i < 3; i++) {
    bloc.add(CounterEvent.decrement);
  }
}
